<?php
class articles_admin_http extends controller_prototype_class
{
	private $_commentsMapper = array();
	private $_entryMapper = array();
	private $_imageMapper;
	private $_blogsMapper;
	private $_mediaMapper;
	private $_structMapper;

	protected $_newsCategoryPageType = 2;
	
    protected $_page = 1;	
    protected $_blog;
    protected $_entry;
    
    protected $actionTitle;
	
    protected function GetCommentsMapper($entryId)
    {
		if (!$this->_commentsMapper[$entryId]) 
		{
			include_once(_APP_PATH. "business/comments/comments_mapper.php");
			$this->_commentsMapper[$entryId] = CommentsMapper::GetInstance($entryId); 
		}
		return $this->_commentsMapper[$entryId];     	
    }    
    
    protected function GetEntryMapper($blogId)
    {
		if (!$this->_entryMapper[$blogId]) 
		{
			include_once(_APP_PATH. "business/articles/article_entry_mapper.php");
			$this->_entryMapper[$blogId] = ArticleEntryMapper::GetInstance($blogId); 
		}
		return $this->_entryMapper[$blogId];     	
    }    

    protected function GetBlogsMapper()
    {
		if (!$this->_blogsMapper) 
		{
			include_once(_APP_PATH. "business/blogs/blogs_mapper.php");
			$this->_blogsMapper = BlogsMapper::GetInstance(); 
		}
		return $this->_blogsMapper;     	
    }    
    
    protected function GetImageMapper()
    {
		if (!$this->_imageMapper) 
		{
			include_once(_APP_PATH. "business/image/image_mapper.php");
			$this->_imageMapper = ImageMapper::GetInstance(); 
		}
		return $this->_imageMapper;     	
    }     
    
    protected function GetMediaMapper()
    {
		if (!$this->_mediaMapper) 
		{
			include_once(_APP_PATH. "business/media/media_mapper.php");
			$this->_mediaMapper = MediaMapper::GetInstance(); 
		}
		return $this->_mediaMapper;     	
    }     

    protected function GetStructMapper()
    {
		if (!$this->_structMapper) 
		{
			include_once(_APP_PATH. "business/structure/structure_mapper.php");
			$this->_structMapper = StructureMapper::GetInstance($this->User()); 
		}
		return $this->_structMapper;     	
    }     
    
    protected function GetBlogFromQueryId()
    {
    	if ($this->_blog !== null) return $this->_blog;

    	$this->_blog = $this->GetBlogsMapper()->GetNew();
    	$this->_blog->SetTitle('Статьи');		

		return $this->_blog;    	
    }    
    
    protected function GetEntryFromQueryId($blogId)
    {
    	if ($this->_entry !== null) return $this->_entry;
    	
		$id = (int)$this->Request()->get('id');	
		if ($id)
		{
			$this->_entry = $this->GetEntryMapper($blogId)->GetById($id);
			return $this->_entry;
		}
		else
		{
			$this->_entry = false;
		}
		
		return $this->_entry;    	
    }    
    
    protected function GetQueryPage()
    {
    	if ($this->Request()->hasQuery('page'))
    	{
			$this->_page = (int)$this->Request()->getQuery('page');
			if ($this->_page != $this->Request()->getCookie('page')) 
			{
				$this->Request()->SetCookie('page', $this->_page, 0, MozgRoute::Get('http')->Create(array('module' => 'admin', 'ctrl' => $this->GetSelfName())));   		
			}
    	}
    	else
    	{
    		$this->_page = (int)$this->Request()->getCookie('page');
    	} 

    	return $this->_page;
    }  

    private $_filter;
    
    protected function GetFilter($blogId)
    {
    	if ($this->_filter) return $this->_filter;
    	
		$this->_filter = $this->GetEntryMapper($blogId)->GetEntryFilter(); 
		
		$filterCategoryStoreName = 'filter_category' .$this->GetSelfName();
		$filterTagStoreName = 'filter_tags' .$this->GetSelfName();
		$filterFromDateStoreName = 'filter_from_date' .$this->GetSelfName();
		$filterToDateStoreName = 'filter_to_date' .$this->GetSelfName();
		
		if ($this->Request()->hasQuery('resetfilter'))
		{
			$this->Libs()->session->SetValue($filterCategoryStoreName, '');
			$this->Libs()->session->SetValue($filterTagStoreName, '');
			$this->Libs()->session->SetValue($filterFromDateStoreName, '');
			$this->Libs()->session->SetValue($filterToDateStoreName, '');
			return $this->_filter;
		}

        if ($this->Request()->hasQuery('filter_category'))
    	{
			$this->Libs()->session->SetValue($filterCategoryStoreName, $this->Request()->getQuery('filter_category')); 
    	}		
		
    	if ($this->Request()->hasQuery('filter_tags'))
    	{
			$this->Libs()->session->SetValue($filterTagStoreName, $this->Request()->getQuery('filter_tags')); 
    	}

        if ($this->Request()->hasQuery('filter_from_date'))
    	{
			$this->Libs()->session->SetValue($filterFromDateStoreName, $this->Request()->getQuery('filter_from_date'));
    	}

        if ($this->Request()->hasQuery('filter_to_date'))
    	{
			$this->Libs()->session->SetValue($filterToDateStoreName, $this->Request()->getQuery('filter_to_date'));
    	}

    	$this->_filter->SetCategory(trim($this->Libs()->session->GetValue($filterCategoryStoreName)));
    	$this->_filter->SetTags(trim($this->Libs()->session->GetValue($filterTagStoreName)));
    	$this->_filter->SetFromDate(trim($this->Libs()->session->GetValue($filterFromDateStoreName)));
    	$this->_filter->SetToDate(trim($this->Libs()->session->GetValue($filterToDateStoreName)));
    	
    	return $this->_filter;
    }
    
    public function GetEntryCut()
    {
		return '<div style="page-break-after: always;"><span style="display: none;">&#160;</span></div>';    	
    }

    public function SplitContent($content)
    {
		return preg_split('/<div[^>]+page-break-after\: always;[^>]+>.*?<\/div>/', $content, 2);		    	
    }
	
    private $_mainThemeEntry = null;
    
    protected function GetMainThemeEntry($blogId)
    {
    	if ($this->_mainThemeEntry !== null) return $this->_mainThemeEntry;
		    	
    	if ($this->Request()->has('main_theme_id'))
    	{
    		$this->Libs()->session->SetValue('mainThemeId', (int)$this->Request()->get('main_theme_id'));
    	}
    	
        if ($this->Libs()->session->GetValue('mainThemeId'))
		{
			$this->_mainThemeEntry = $this->GetEntryMapper($blogId)->GetById($this->Libs()->session->GetValue('mainThemeId'));
			if (!$this->_mainThemeEntry) $this->Libs()->session->SetValue('mainThemeId', 0);
		}    
		else
		{
			$this->_mainThemeEntry = false;	
		}
    	
    	return $this->_mainThemeEntry;
    }

    protected function OutArticles($blog)
    {
    	$this->GetQueryPage();

        $this->actionTitle = $blog->GetTitle();

        $filter = $this->GetFilter($blog->GetId());       

        $onPage = MozgCfg::GetProp('admin/articles//perPage');
               
        $paginator = SysLoader::GetModule('controlls', 'http', '_web')->GetCtrl('paginator');
        $pattern = MozgRoute::Get('http')->Create(array('module' => 'admin', 
			        									 'ctrl' => $this->GetSelfName(), 
			        									 'action' => 'out_articles', 
			        									 'blog' => $blog->GetId(), 
			        									 'page' => '__page__'));
        $paginator->SetUrlPattern($pattern);         
        $pagMapper = $paginator->GetMapper();
        $pagMapper->Set(0, $this->_page, $onPage);
        
        $entries = $this->GetEntryMapper($blog->GetId())->GetEntries($pagMapper, $filter);
        $pagMapper->SetTotalCount($this->GetEntryMapper($blog->GetId())->GetTotalEntries());               
        
        $t = $this->GetTemplator();
        $t->ctrlName = $this->GetSelfName();
        $t->blog = $blog;
        $t->entries = $entries;
        $t->page = $this->_page;
        $t->pages = $paginator->Generate();
        $t->mainThemeEntry = $this->GetMainThemeEntry($blog->GetId());
        $this->LoadTemplate($t->render('articles/_articles.phtml'));
        
        $this->GetModule()->GetDecorator()->SetSecondAction('Left Sidebar', 'OutFilterInBlock', $this->GetSelfName());
        $this->GetModule()->GetDecorator()->SetSecondAction('Right Sidebar', 'OutThemeInBlock', $this->GetSelfName());        
    } 

    protected function AddArticle($blog, $entry = null)
    {
        $this->actionTitle = $blog->GetTitle();

        if (!$entry)
        {
        	$entry = $this->GetEntryFromQueryId($blog->GetId());
	   		if (!$entry) $entry = $this->GetEntryMapper($blog->GetId())->GetNew();
        }        
        
        $t = $this->GetTemplator();
        $t->ctrlName = $this->GetSelfName();
        $t->blog = $blog;
        $t->entry = $entry;
        $t->entryCut = $this->GetEntryCut();
        $t->thumbFolder = $this->GetPhotoThumbFolder('mediathumbnail');
        $t->newsCategoryIds = $this->GetStructMapper()->GetIdsByType($this->_newsCategoryPageType);
        $t->structMapper = $this->GetStructMapper();
        $t->filter = $this->GetFilter($t->blog->GetId());
        $this->LoadTemplate($t->render('articles/_addarticle.phtml'));
        
        $baseUrlParams = array(
        						'module' => 'admin',
        						'ctrl' => $this->GetSelfName(), 
        						'action' => 'media_add_article', 
        						'blog' => $blog->GetId(), 
        						'id' => $entry->GetId()
        					);
        					
        $this->GetModule()->GetDecorator()->SetSecondAction('Left Sidebar', 'media_blockSc', 'media', array('baseUrl' => $baseUrlParams, 'params' => array('contentButton' => true, 'addButtonCallback' => 'addArticleMainMediaFile')));    	
    }  

    protected function MediaForArticle($blog)
    {
    	$entry = $this->GetEntryFromQueryId($blog->GetId());
    	
        $obj = SysLoader::GetModResponse();

        $baseUrlParams = array(
        						'module' => 'admin',
        						'ctrl' => $this->GetSelfName(), 
        						'action' => 'media_add_article', 
        						'blog' => $blog->GetId(), 
        						'id' => $entry ? $entry->GetId() : 0,
        					);        
        
		$obj->SetStatus(MR_STATUS_OK);
		$obj->result = $this->_ctrls->media->OutMediaFilesBlock($baseUrlParams, array('contentButton' => true, 'addButtonCallback' => 'addArticleMainMediaFile'));

        $this->Response()->SetBody($obj);    	
    }
    
    protected function SaveArticle($blog)
    {
       	$entry = $this->GetEntryFromQueryId($blog->GetId());
   		if (!$entry) $entry = $this->GetEntryMapper($blog->GetId())->GetNew();

        $entry->SetTitle(trim($this->Request()->getPost('title')));
        $entry->SetPublishDate(trim($this->Request()->getPost('publish_date')));

        $entry->SetBrief(trim($this->Request()->getPost('brief')));
		$entry->SetContent(trim($this->Request()->getPost('content')));
		$entry->SetTags(trim($this->Request()->getPost('tags')));
		
		if (!$blog->GetId())
		{
			$entry->SetIsMain((int)$this->Request()->getPost('is_main') ? 1 : 0);
			$entry->SetUrl($this->Request()->getPost('url'));			
			$entry->SetCategories((array)$this->Request()->getPost('category'));
		}
			
		$mediaFileId = (int)$this->Request()->getPost('media_file_id');
		if ($mediaFileId)
		{
			$mediaFileObj = $this->GetMediaMapper()->GetById($mediaFileId);
		}
		else
		{
			$mediaFileObj = $this->GetMediaMapper()->GetNew();
		}
		
		$entry->SetMediaFile($mediaFileObj);
		
		if ($this->GetEntryMapper($blog->GetId())->Save($entry)) 
        {	  
        	$themeEntryIds = (array)$this->Request()->getPost('theme_entries');
        	$this->GetEntryMapper($blog->GetId())->SaveThemeEntries($entry->GetId(), $themeEntryIds);
            
        	$this->Libs()->messanger->createMessage('Данные сохранены');
        	
        	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => $this->GetSelfName(), 
		        									 'action' => 'out_articles', 
		        									 'blog' => $blog->GetId()));        	
        } 
        else
        {
        	if ($this->GetEntryMapper($blog->GetId())->IsError())
        	{
        		$this->Libs()->messanger->createMessage($this->GetEntryMapper($blog->GetId())->GetErrorMessage(), MESSAGE_ERROR);
        	}
        	else
        	{
        		$this->Libs()->messanger->createMessage('Данные не были сохранены', MESSAGE_ERROR);    		
        	}
        	
        	$this->AddArticle($blog, $entry);
        	return;
        }
    } 

    protected function DelArticle($blog)
    {
       	$entry = $this->GetEntryFromQueryId($blog->GetId());
   		if (!$entry)
   		{
   			$this->Libs()->messanger->createMessage('Статья не найдена', MESSAGE_ERROR);
        	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => $this->GetSelfName(), 
		        									 'action' => 'out_articles', 
		        									 'blog' => $blog->GetId()));   			   				   		
   		}   

   		if ($this->GetEntryMapper($blog->GetId())->Delete($entry->GetId()))
   		{
			$this->Libs()->messanger->createMessage('Статья удалёна');   			
   		}
   		else
   		{
			$this->Libs()->messanger->createMessage('Не удалось удалить статью', MESSAGE_ERROR);   			
   		}
   		
       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
	        									 'ctrl' => $this->GetSelfName(), 
	        									 'action' => 'out_articles', 
	        									 'blog' => $blog->GetId()));   		   	
    } 

    protected function SaveThemeArticles($blog)
    {
    	$entry = $this->GetMainThemeEntry($blog->GetId());
		if (!$entry) 
		{
        	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => $this->GetSelfName(), 
		        									 'action' => 'out_articles', 
		        									 'blog' => $blog->GetId()));			
		}
    	
		$themeEntryIds = (array)$this->Request()->getPost('theme_id');
		$this->GetEntryMapper($blog->GetId())->AddThemeEntries($entry->GetId(), $themeEntryIds);
		
       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
	        									 'ctrl' => $this->GetSelfName(), 
	        									 'action' => 'out_articles', 
	        									 'blog' => $blog->GetId()));		
    }

    protected function DelThemeArticle($blog)
    {
    	$entry = $this->GetMainThemeEntry($blog->GetId());
		if (!$entry) 
		{
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => $this->GetSelfName(), 
		        									 'action' => 'out_articles', 
		        									 'blog' => $blog->GetId()));				
		}
    	
		$themeEntryId = (int)$this->Request()->getQuery('theme_id');
		$this->GetEntryMapper($blog->GetId())->DelThemeEntry($entry->GetId(), $themeEntryId);
		
       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
	        									 'ctrl' => $this->GetSelfName(), 
	        									 'action' => 'out_articles', 
	        									 'blog' => $blog->GetId()));			  	
    }

    protected function OutComments($blog)
    {
    	$entry = $this->GetEntryFromQueryId($blog->GetId());
    	
        $this->actionTitle = 'Комментарии';

        $t = $this->GetTemplator();
        $t->ctrlName = $this->GetSelfName();
        $t->blog = $blog;
        $t->entry = $entry;
        $t->comments = $this->GetCommentsMapper($entry->GetId())->GetComments();
        $this->LoadTemplate($t->render('articles/_comments.phtml'));

        $this->GetModule()->GetDecorator()->SetSecondAction('Right Sidebar', 'OutArticleInfoInBlock', $this->GetSelfName());     	
    }
    
    protected function DelComment($blog)
    {
    	$entry = $this->GetEntryFromQueryId($blog->GetId());
		if (!$entry) 
		{
			$this->Libs()->messanger->createMessage('Статья не найдена', MESSAGE_ERROR);
	       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
		        									 'ctrl' => $this->GetSelfName(), 
		        									 'action' => 'out_articles', 
		        									 'blog' => $blog->GetId()));				
		}
    	
		$commentId = (int)$this->Request()->getQuery('comment');
		if ($this->GetCommentsMapper($entry->GetId())->Delete($commentId))
		{
			$this->Libs()->messanger->createMessage('Комментарий удалён');
		}
		
       	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 
	        									 'ctrl' => $this->GetSelfName(), 
	        									 'action' => 'out_comments', 
	        									 'blog' => $blog->GetId(), 
	        									 'id' => $entry->GetId()));			     	
    }
    
    private function OutFilter()
    {
        $t = $this->GetTemplator();
        $t->ctrlName = $this->GetSelfName();
        $t->blog = $this->GetBlogFromQueryId();
        $t->filter = $this->GetFilter($t->blog->GetId());
        $t->newsCategoryIds = $this->GetStructMapper()->GetIdsByType($this->_newsCategoryPageType);
        $t->structMapper = $this->GetStructMapper();        
        return $t->render('articles/_filter_form.phtml');     	
    }

    public function OutFilterInBlock()
    {
        $t = $this->GetTemplator();
        $t->title = 'Фильтр';
        $t->content = $this->OutFilter();
        return $t->render('_left_block_template.phtml');
    }         
    
    private function OutTheme()
    {
    	$blog = $this->GetBlogFromQueryId();
    	$entry = $this->GetMainThemeEntry($blog->GetId());
    	if (!$entry) return false;

        $t = $this->GetTemplator();
        $t->ctrlName = $this->GetSelfName();
        $t->blog = $blog;
        $t->entry = $entry;
        $t->themeEntries = $this->GetEntryMapper($blog->GetId())->GetThemeEntries($entry->GetId());
        return $t->render('articles/_out_theme_block.phtml');     	
    }    
    
    public function OutThemeInBlock()
    {
    	$content = $this->OutTheme();
    	if ($content === false) return '';
    	
        $t = $this->GetTemplator();
        $t->title = 'Статьи по теме';
        $t->content = $content;
        return $t->render('_right_block_template.phtml');     	
    }    
    
    private function OutArticleInfo()
    {
    	$blog = $this->GetBlogFromQueryId();
    	$entry = $this->GetEntryFromQueryId($blog->GetId());
    	if (!$entry) return false;

        $t = $this->GetTemplator();
        $t->ctrlName = $this->GetSelfName();
        $t->blog = $blog;
        $t->entry = $entry;
        return $t->render('articles/_out_article_info.phtml');     	
    }    
    
    public function OutArticleInfoInBlock()
    {
        $t = $this->GetTemplator();
        $t->title = 'Статья';
        $t->content = $this->OutArticleInfo();
        return $t->render('_right_block_template.phtml');     	
    }     
    
    protected function LoadTemplate ($content)
    {
        $t = $this->GetTemplator();
        $t->title = $this->actionTitle;
        $t->content = $content;
        $this->Response()->SetBody($t->render('_main_block_template.phtml'));
    } 

    const MAX_TAGS_IN_LIST = 30;
    
    public function TagsList($blog)
    {
    	$name = trim(urldecode($this->Request()->getPost('tag')));
    	$max = (int)$this->Request()->getPost('max');
		$tags = $this->GetEntryMapper($blog->GetId())->GetTagsByName($name, min($max, self::MAX_TAGS_IN_LIST));    	

		$preparedData = array();
		$i = 0;
		foreach ($tags as $tagName)
    	{
			$preparedData[$i] = new stdClass(); 
			$preparedData[$i]->tag = $tagName;  
			$i++; 		
    	}
		
        $this->Response()->SetBody($this->Libs()->json->encode($preparedData));
        $this->GetModule()->GetDecorator()->SetTemplate('SimpleJson'); 	
    }  

    public function GetPhotoThumbFolder($thumbFolder)
    {
        return $this->GetImageMapper()->GetImageThumbFolder($thumbFolder);      
    }    
}    